#include "kjsonread.h"

#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkRequest>
#include <QJsonValue>

KJsonRead::KJsonRead(QObject* parent)
    : QObject(parent)
    , m_pNetworkManager(new QNetworkAccessManager(this))
{
    connect(m_pNetworkManager, &QNetworkAccessManager::finished,
        this, &KJsonRead::onReplyFinished);
}

KJsonRead::~KJsonRead()
{
}

void KJsonRead::fetchFromUrl(const QUrl& url)
{
    QNetworkRequest request(url);
    m_pNetworkManager->get(request);
}

void KJsonRead::onReplyFinished(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(data, &err);
        if (err.error == QJsonParseError::NoError && doc.isObject()) {
            m_tipMap.clear();
            QJsonObject root = doc.object();
            for (const QString& key : root.keys()) {
                QJsonObject obj = root[key].toObject();
                QString title = obj.value("title").toString();
                QString desc = obj.value("text").toString();
                m_tipMap[key] = qMakePair(title, desc);
            }
            emit jsonReady();
        }
    }
    reply->deleteLater();
}

QString KJsonRead::getTitle(const QString& key) const
{
	if(m_tipMap.contains(key))
		return m_tipMap.value(key).first;
	if(m_fallbackMap.contains(key))
		return m_fallbackMap.value(key).first;
	return {};
}

QString KJsonRead::getDescription(const QString& key) const
{
	if(m_tipMap.contains(key))
		return m_tipMap.value(key).second;
	if(m_fallbackMap.contains(key))
		return m_fallbackMap.value(key).second;
	return {};
}

bool KJsonRead::loadFallbackJson(const QString& path)
{
	QFile file(path);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
		return false;

	QByteArray data = file.readAll();
	  file.close();

	QJsonParseError err;
	QJsonDocument doc = QJsonDocument::fromJson(data, &err);
	if (err.error != QJsonParseError::NoError || !doc.isObject())
		return false;

	QJsonObject root = doc.object();
	for (const QString& key : root.keys()) {
		QJsonObject obj = root[key].toObject();
		QString title = obj.value("title").toString();
		QString desc = obj.value("text").toString();
		m_fallbackMap[key] = qMakePair(title, desc);
	}
	return true;
}

QObject* KJsonRead::asQObject()
{
	return this;
}
